<?

class Solr_manager {
    public $CI;
    public $doc;
    public $options;
    public $client;
    public $query;
    public $solr_server;
    public $update_cmd;
    public $e = 0;
    
    public function __construct(){
        $this->CI =& get_instance();
        
        $this->solr_server = $solr_server = "http://" . $this->CI->config->item("SOLR_SERVER_HOSTNAME") .  ":" . $this->CI->config->item("SOLR_SERVER_PORT") . "/" . $this->CI->config->item("SOLR_SERVER_PATH") . "/";
        
        $this->update_cmd = "update?optimize=true&waitFlush=true&waitSearcher=true&expungeDeletes=true";
        
        $this->options = array(
            'hostname' => $this->CI->config->item("SOLR_SERVER_HOSTNAME"),
            'port'     => $this->CI->config->item("SOLR_SERVER_PORT")
        );
        $this->client = new SolrClient($this->options);
        
        $this->query = new SolrQuery();
        
    }
    
    public function remove_feed_by_id($id){
    	//Remove the documents in this feed
    	$this->CI->db->query("UPDATE feeds SET last_index = ? WHERE ID = ?", array('0', $id));
        $this->delete_by_query("feed_id:" . $id);

    }
    
    public function index_feed_by_id($id, $commit = FALSE){   
    	set_time_limit(0); 	
    	
    	$sel_feed = $this->CI->db->query("SELECT feed_topic, feed_url, feed_type, feed_program, feed_station FROM feeds WHERE ID = '".$id."' LIMIT 1");
    	$res_feed = $sel_feed->row();
    	$url = $res_feed->feed_url;
    	
        $items = $this->CI->feed_parser->parse($url);
    	
    	//First Parse the feed
    	echo "<b>Parsing feed: <a target='_blank' href='".$url."'>".$url."</a></b><br />\n";
    	flush();
    	
    	if(is_array($items)){
    		
	     	foreach($items as $item){
	    		$this_program = $res_feed->feed_program;
	    		$this_station = $res_feed->feed_station;
	
	    		/*
	    		 * Ciprian note:
	    		 * Just make up a unique document id for the index.
	    		 * This is a computation of the feed content.
	    		 * If this is not unique than the document will be updated
	    		 * If this is unique the document will be added as new
	    		*/
	    		$doc_id = md5($item['title'] . $item['link'] . $item['description']);
	    		
	    		$exists = $this->query("id:" . $doc_id);
	    		
	    		if($exists->response->numFound == 0){
	    		
		    		$fields = array();
		    		$fields['feed_id'] = $id;
		    		$fields['id'] = $doc_id;
		    		$fields['title'] = $item['title'];
		    		$fields['url'] = $item['link'];
		    		$fields['description'] = $item['description'];
		    		$fields['keywords'] = $item['keywords'];
		    		if($item['pubdate']){
		    		   $fields['date'] = $item['pubdate'];
		    		}
		    		$fields['category'] = $item['category'];
		    		$fields['object_type'] = $res_feed->feed_type;
		    		$fields['program'] = $this_program;
		    		$fields['station'] = $this_station;
		    		$fields['topic'] = $res_feed->feed_topic;
		    		echo "Adding: <i>".$item['title']."</i>...<br />\n";
		    		flush();
		    		$this->add_doc($fields);
		    		
		    		if($this->e == 5){
		    			$this->commit_index();
		    			$this->e = 0;
		    		}
		    		
		    		$this->e++;
	    		}else{
	    			echo "<span style='color:red; font-size:11px; font-weight:bold;'>Skipping duplicate: " . $item['title'] . "</span></br>\n";
	    			flush();
	    		}
	    	}
    	}
        if($commit == TRUE){
        	$this->CI->db->query("UPDATE feeds SET last_index = ? WHERE ID = ?", array(time(), $id));
	        $this->commit_index($id);
	        
        }
    }
    
    
    public function remove_all_feeds(){
        $sel = $this->CI->db->query("SELECT * FROM feeds");
        $res = $sel->result();
        foreach($res as $rss){
            $this->remove_feed_by_id($rss->ID);
            unset($rss->ID);
        }
    }
    
    
    public function add_doc($fields, $commit = FALSE){
    	$this->doc = new SolrInputDocument();
    	foreach($fields as $key=>$val){
	        $this->doc->addField($key, $val);
    	}
    	$this->client->addDocument($this->doc);
    	if($commit == TRUE){
    		$ret = $this->commit_index();
    		return $ret;
    	}
    }
    
    public function delete_by_id($id, $commit = FALSE){
    	$ret = $this->client->deleteById($id);
        if($commit == TRUE){
            $ret = $this->commit_index();
        }
        return $ret;
    }
    
    public function delete_by_query($query, $commit = FALSE){
    	$ret = $this->client->deleteByQuery($query);
    	if($commit == TRUE){
            $ret = $this->commit_index();
        }
        return $ret;
    }
    
    public function commit_index($id = FALSE){
        if($id != FALSE){
            if($id == "all"){
                $this->CI->db->query("UPDATE feeds SET last_index = ?", array(time()));
            }else{
                $this->CI->db->query("UPDATE feeds SET last_index = ? WHERE ID = ?", array(time(), $id));
            }
        }
        
    	echo "Committing index...<br />\n";
    	flush();
    	$this->client->commit();
    	echo "<b>DONE</b>\n<br />\n";
    	flush();
    	//try{
    	   //@$this->optimize_index();
    	//}catch (Exception $e){
    		//echo '<b>DONE</b><br />';
    	//}
    	   	
    }
    
    public function optimize_index(){
    	echo "Optimizing index...<br />\n";
        flush();
        $ret = $this->CI->curl_post->get($this->solr_server . $this->update_cmd);
        echo $ret . "<br />";
        echo "<b>DONE</b>\n<br />\n";
    }
    
    public function query($keywords, $start = 0, $rows_num = 10, $fields = array('topic', 'id','title', 'description', 'keywords', 'url', 'score', 'program', 'station', 'date','object_type')){
    	
        foreach($fields as $field){
            $this->query->addField($field);
        }
        $this->query->addField('score');
        
    	$this->query->setQuery($keywords);
    	
        $this->query->setStart($start);
        $this->query->setRows($rows_num);
        
        
        
        $query_response = $this->client->query($this->query);
        $response = $query_response->getResponse();
        
        return $response;
    }
    
    
    
}



?>